<?php
class Controller_Login extends Controller_Template
{
	public function __construct()
	{
		parent::__construct();
		$this->selfModel = new Model_MapperAssociation("association", parent::$db);
	}

        public function login()
	{
            $loginform = new Formulaire('login', '#', 'POST');
            $loginform->addAttribut('id', 'login_form');

            $login = new ChampText('login', 'Login', true);
            $password = new ChampPassword('password', 'Password', true);
            $submit = new ChampSubmit('submit', 'Se connecter');
            $submit->addAttribut('class', 'button');

            $loginform->addChamp($login);
            $loginform->addChamp($password);
            $loginform->addChamp($submit);

            if(isset($_POST['formid']) && !empty($_POST['formid']) )
            {
                //formulaire soumis on recharge les valeurs et on valide le formulaire
                $loginform->bind();

                if($loginform->valider() )
                {
                    //validation du login mot de passe
                    $assoc = $this->selfModel->getOneByLogin($login->getValeur());

                    if(!is_null($assoc) && $assoc->login($password->getValeur()))
                    {
                        $_SESSION['idassoc'] = $assoc->getId_association();
                        header("Location: admin/index.html\n\n");
                    }
                    else
                    {
                        echo $password->getValeur();
                        echo "LOGIN INCORRECT!";
                        echo $loginform->render();
                    }
                }
                else
                {
                    echo "Erreurs</br>";
                    foreach($loginform->getChamps() as $champ)
                    {
                        if($champ->isvalid == false)
                        {
                            echo $champ . ' : <br/>';

                            foreach($champ->getErreurs() as $erreur)
                            {
                                echo $erreur . '<br/>';
                            }
                        }
                    }

                    echo $loginform->render();
                }
            }
            else
            {
                echo $loginform->render();
            }
	}

        public function logout()
        {
            $_SESSION = array(); // on réécrit le tableau
            session_destroy(); // on détruit le tableau réécrit
            header("Location: admin/index.html\n\n");
        }
}
?>
